package framework.utils;

/**
 * 路径工具
 */
public class PathUtil {

    /**
     * 清理父级目录，以及父目录保护
     *
     * @param path
     * @return
     */
    public static String cleanParentPath(String path) {
        path = path.replace("..", "");
        path = path.replace("//", "/");
        path = path.replace("\\\\", "//");
        path = removeFirstSlash(path);
        return path;
    }

    /**
     * 去除路径中首字符的分隔符
     *
     * @param path
     * @return
     */
    public static String removeFirstSlash(String path) {
        if (path == null) return null;
        if (path.equals("")) return path;
        while (true) {
            if (path.startsWith("/")) {
                path = path.substring(1);
                continue;
            } else if (path.startsWith("\\")) {
                path = path.substring(1);
                continue;
            } else {
                break;
            }
        }
        return path;
    }

    /**
     * 去除路径中尾字符的分隔符
     *
     * @param path
     * @return
     */
    public static String removeEndSlash(String path) {
        if (path == null) return null;
        if (path.equals("")) return path;
        while (true) {
            if (path.endsWith("/")) {
                path = path.substring(0, path.length() - 1);
                continue;
            } else if (path.endsWith("\\")) {
                path = path.substring(1, path.length() - 1);
                continue;
            } else {
                break;
            }
        }
        return path;
    }

    /**
     * 添加路径中首字符的分隔符
     *
     * @param path
     * @return
     */
    public static String appendFirstSlash(String path) {
        if (path == null) return null;
        if (path.equals("")) return path;
        if (path.startsWith("/")) return path;
        if (path.startsWith("\\")) return path;
        return "/" + path;
    }

    /**
     * 添加路径中尾字符的分隔符
     *
     * @param path
     * @return
     */
    public static String appendEndSlash(String path) {
        if (path == null) return null;
        if (path.equals("")) return path;
        if (path.endsWith("/")) return path;
        if (path.endsWith("\\")) return path;
        return path + "/";
    }

}
